<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="Shinya"><meta name="copyright" content="Shinya"><meta name="generator" content="Hexo 5.4.0"><meta name="theme" content="hexo-theme-yun"><title>除以2和右移1位的区别 | 夤夜的世界旅行手记</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.24/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_j5gk85dg4pf.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>document.addEventListener("DOMContentLoaded", () => {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
});
</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script defer src="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/contrib/copy-tex.min.css"><script defer src="https://cdn.jsdelivr.net/npm/katex@latest/dist/contrib/copy-tex.min.js"></script><script defer src="https://cdn.jsdelivr.net/npm/katex@latest/dist/contrib/auto-render.min.js"></script><script>document.addEventListener("DOMContentLoaded", () => {
  Yun.utils.renderKatex();
});</script><link id="light-prism-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@latest/themes/prism.css" media="(prefers-color-scheme: light)"><link id="dark-prism-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@latest/themes/prism-tomorrow.css" media="(prefers-color-scheme: dark)"><link rel="icon" href="https://upimage.alexhchu.com/2021/04/19/abe22a9e40f16.jpg"><link rel="mask-icon" href="https://upimage.alexhchu.com/2021/04/19/abe22a9e40f16.jpg" color="#0078E7"><link rel="alternate icon" href="/yun.ico"><link rel="preload" href="/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/js/utils.js" as="script"><link rel="preload" href="/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"hostname":"shinya754.gitee.io","root":"/","title":"夤夜的世界旅行手记","version":"1.6.1","mode":"time","copycode":true,"page":{"isPost":true},"i18n":{"placeholder":"搜索...","empty":"找不到您查询的内容: ${query}","hits":"找到 ${hits} 条结果","hits_time":"找到 ${hits} 条结果（用时 ${time} 毫秒）"},"anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"fireworks":{"colors":["153, 153, 255","255, 255, 0","51, 255, 0"]}};
  </script><link rel="stylesheet" href="/css/hexo-theme-yun.css"><script src="/js/utils.js"></script><script src="/js/hexo-theme-yun.js"></script><meta name="description" content="“&#x2F;2”和”&gt;&gt;1”的区别&amp;emsp;写优先级队列的时候发现，-1&#x2F;2的值为0，当时是在一个循环中将一个值&#x2F;2再-1，然后循环执行，结果进入死循环了。&amp;emsp;改成&gt;&gt;1后，不再死循环，原因是-1 &gt;&gt; 1 &#x3D; -1。&amp;emsp;于是百度了一下两者的区别，找到了这个：">
<meta property="og:type" content="article">
<meta property="og:title" content="除以2和右移1位的区别">
<meta property="og:url" content="https://shinya754.gitee.io/2021/04/07/%E9%99%A4%E4%BB%A52%E5%92%8C%E5%8F%B3%E7%A7%BB1%E4%BD%8D%E7%9A%84%E5%8C%BA%E5%88%AB/index.html">
<meta property="og:site_name" content="夤夜的世界旅行手记">
<meta property="og:description" content="“&#x2F;2”和”&gt;&gt;1”的区别&amp;emsp;写优先级队列的时候发现，-1&#x2F;2的值为0，当时是在一个循环中将一个值&#x2F;2再-1，然后循环执行，结果进入死循环了。&amp;emsp;改成&gt;&gt;1后，不再死循环，原因是-1 &gt;&gt; 1 &#x3D; -1。&amp;emsp;于是百度了一下两者的区别，找到了这个：">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-07T15:14:37.000Z">
<meta property="article:modified_time" content="2021-04-18T10:38:29.432Z">
<meta property="article:author" content="Shinya">
<meta property="article:tag" content="学习">
<meta property="article:tag" content="计组">
<meta name="twitter:card" content="summary"><script src="/js/ui/mode.js"></script></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest"></script><script defer src="/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="文章目录"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="站点概览"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/about/" title="Shinya"><img width="96" loading="lazy" src="https://upimage.alexhchu.com/2021/04/19/abe22a9e40f16.jpg" alt="Shinya"><span class="site-author-status" title="You'll see this world is wonderful.">😊</span></a><div class="site-author-name"><a href="/about/">Shinya</a></div><span class="site-name">夤夜的世界旅行手记</span><sub class="site-subtitle">你好，陌生人。</sub><div class="site-desciption">某211软工专业在读</div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/" title="首页"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/archives/" title="归档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">23</span></a></div><div class="site-state-item"><a href="/categories/" title="分类"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">4</span></a></div><div class="site-state-item"><a href="/tags/" title="标签"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">12</span></a></div><a class="site-state-item hty-icon-button" target="_blank" rel="noopener" href="http://121.4.147.128:8888/profile?id=%E5%A4%8F%E8%89%B2%E5%8D%83%E7%BB%AB" title="TOS战绩"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-open-arm-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://github.com/Shinya754" title="GitHub" target="_blank" style="color:#6e5494"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-github-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://music.163.com/#/user/home?id=114080703" title="网易云音乐" target="_blank" style="color:#C20C0C"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-netease-cloud-music-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://www.zhihu.com/people/yin-ye-14-16" title="知乎" target="_blank" style="color:#0084FF"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-zhihu-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://space.bilibili.com/4950796" title="哔哩哔哩" target="_blank" style="color:#FF8EB3"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-bilibili-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://twitter.com/Shinya433" title="Twitter" target="_blank" style="color:#1da1f2"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-twitter-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="mailto:shinya754@qq.com" title="E-Mail" target="_blank" style="color:#8E71C1"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-mail-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/links/" title="我的小伙伴们" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div><br><a class="links-item hty-icon-button" id="toggle-mode-btn" href="javascript:;" title="Mode" style="color: #f1cb64"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-contrast-2-line"></use></svg></a></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E2%80%9C-2%E2%80%9D%E5%92%8C%E2%80%9D-gt-gt-1%E2%80%9D%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">1.</span> <span class="toc-text">“&#x2F;2”和”&gt;&gt;1”的区别</span></a></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="hty-card post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="https://shinya754.gitee.io/2021/04/07/%E9%99%A4%E4%BB%A52%E5%92%8C%E5%8F%B3%E7%A7%BB1%E4%BD%8D%E7%9A%84%E5%8C%BA%E5%88%AB/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="Shinya"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="夤夜的世界旅行手记"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">除以2和右移1位的区别</h1><div class="post-meta"><div class="post-time" style="display:inline-block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="创建时间：2021-04-07 23:14:37" itemprop="dateCreated datePublished" datetime="2021-04-07T23:14:37+08:00">2021-04-07</time><span class="post-meta-divider">-</span><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-2-line"></use></svg></span> <time title="修改时间：2021-04-18 18:38:29" itemprop="dateModified" datetime="2021-04-18T18:38:29+08:00">2021-04-18</time></div><div class="post-classify"><span class="post-tag"><a class="tag-item" href="/tags/%E5%AD%A6%E4%B9%A0/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">学习</span></a><a class="tag-item" href="/tags/%E8%AE%A1%E7%BB%84/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">计组</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><h4 id="“-2”和”-gt-gt-1”的区别"><a href="#“-2”和”-gt-gt-1”的区别" class="headerlink" title="“/2”和”&gt;&gt;1”的区别"></a>“/2”和”&gt;&gt;1”的区别</h4><p>&emsp;写优先级队列的时候发现，<code>-1/2</code>的值为<code>0</code>，当时是在一个循环中将一个值<code>/2</code>再<code>-1</code>，然后循环执行，结果进入死循环了。<br>&emsp;改成<code>&gt;&gt;1</code>后，不再死循环，原因是<code>-1 &gt;&gt; 1 = -1</code>。<br>&emsp;于是百度了一下两者的区别，找到了<a target="_blank" rel="noopener" href="https://zhidao.baidu.com/question/559478853089880364.html">这个</a>：</p>
<span id="more"></span>
<blockquote>
<p>&emsp;编译器不会将“/2”优化为“&gt;&gt;1”，因为当被除数为负数时，/2会向上取整，&gt;&gt;1会向下取整。<br>&emsp;即：“/2“为“向零取整”，“&gt;&gt;1”永远向下取整。<br>&emsp;由于两个操作效果有差异，当被除数为变量时编译器不知道它是不是负数，无法将两个操作等效，不敢优化。<br>&emsp;要是被除数是常量的话，编译器可以直接在编译期算完结果，不在运行期算，这时候效率是一样的，因为都不用计算（也许，万一编译器不优化咱也没处说理啊）。</p>
</blockquote>
<p>&emsp;于是简单研究了一下二者的原理：</p>
<pre class="language-csharp" data-language="csharp"><code class="language-csharp"><span class="token class-name"><span class="token keyword">int</span></span> a <span class="token operator">=</span> <span class="token operator">-</span><span class="token number">5</span><span class="token punctuation">;</span>
Console<span class="token punctuation">.</span><span class="token function">WriteLine</span><span class="token punctuation">(</span>a <span class="token operator">/</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
Console<span class="token punctuation">.</span><span class="token function">WriteLine</span><span class="token punctuation">(</span>a <span class="token operator">>></span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>得到的结果是<code>-2</code>和<code>-3</code><br>&emsp;除法不知道具体是怎么实现的，但是右移这个操作还是可以合理推断一下的。<br>&emsp;已知在计算机中，数字由<code>补码</code>的形式存储，那么<code>-5</code>这个数在存储时就应该是<code>1011</code>（简便起见使用4位二进制来表示数字，其中第一位是符号位）<br>&emsp;而将<code>-5</code>右移一位后，最低位数字被舍弃，<strong>最高位补上符号位</strong>，其结果为<code>1101</code>，转化为十进制就是<code>-3</code>。<br>&emsp;<code>/2</code>这个操作只能靠猜了。从前面百度的结果来看，一个数<code>/2</code>后总会向<code>0</code>取整，那么<code>/2</code>可能是先做一次右移操作（通过计组的学习可以知道计算机中的乘除法都是通过<code>移位</code>操作来实现的，这样可以加快运行速度），当结果为负数且小数部分不为0时，舍弃小数部分后+1以实现向0取整。</p>
</div><div id="reward-container"><span class="hty-icon-button button-glow" id="reward-button" title="打赏" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === &quot;none&quot;) ? &quot;block&quot; : &quot;none&quot;;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-hand-coin-line"></use></svg></span><div id="reward-comment">希望我提供的帮助能够补偿你在这里花费的时间。</div><div id="qr" style="display:none;"><div style="display:inline-block"></div></div></div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong>Shinya</li><li class="post-copyright-link"><strong>本文链接：</strong><a href="https://shinya754.gitee.io/2021/04/07/%E9%99%A4%E4%BB%A52%E5%92%8C%E5%8F%B3%E7%A7%BB1%E4%BD%8D%E7%9A%84%E5%8C%BA%E5%88%AB/" title="除以2和右移1位的区别">https://shinya754.gitee.io/2021/04/07/%E9%99%A4%E4%BB%A52%E5%92%8C%E5%8F%B3%E7%A7%BB1%E4%BD%8D%E7%9A%84%E5%8C%BA%E5%88%AB/</a></li><li class="post-copyright-license"><strong>版权声明：</strong>本博客所有文章除特别声明外，均默认采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> 许可协议。</li></ul></section></article><div class="post-nav"><div class="post-nav-item"><a class="post-nav-prev" href="/2021/04/08/%E5%8A%9B%E6%89%A3153-%E5%AF%BB%E6%89%BE%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC/" rel="prev" title="力扣153. 寻找旋转排序数组中的最小值"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-left-s-line"></use></svg><span class="post-nav-text">力扣153. 寻找旋转排序数组中的最小值</span></a></div><div class="post-nav-item"><a class="post-nav-next" href="/2021/04/07/%E5%8A%9B%E6%89%A381-%E6%90%9C%E7%B4%A2%E6%97%8B%E8%BD%AC%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84II/" rel="next" title="力扣81. 搜索旋转排序数组II"><span class="post-nav-text">力扣81. 搜索旋转排序数组II</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div><div class="hty-card" id="comment"><div class="comment-tooltip text-center"><span>这里是大图书馆的留言板，请友善地发言。</span><br></div><div id="valine-container"></div><script>Yun.utils.getScript("https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js", () => {
  const valineConfig = {"enable":true,"appId":"O3v2IWIbQY4NT5SuPUNEWOSt-MdYXbMMI","appKey":"bsHhi7jpWfTk1P3dkHeHjBTz","placeholder":"建议设置回复时使用的昵称哦","avatar":null,"meta":["nick"],"pageSize":10,"visitor":false,"highlight":true,"recordIP":false,"enableQQ":true,"el":"#valine-container","lang":"zh-cn"}
  valineConfig.path = "/2021/04/07/%E9%99%A4%E4%BB%A52%E5%92%8C%E5%8F%B3%E7%A7%BB1%E4%BD%8D%E7%9A%84%E5%8C%BA%E5%88%AB/"
  new Valine(valineConfig)
}, window.Valine);</script></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2021 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> Shinya</span></div><div class="powered"><span>由 <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> 驱动 v5.4.0</span><span class="footer-separator">|</span><span>主题 - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v1.6.1</span></div><div class="live_time"><span>大图书馆已经观察并记录这个世界</span><span id="display_live_time"></span><span class="moe-text">(●'◡'●)</span><script>function blog_live_time() {
  setTimeout(blog_live_time, 1000);
  const start = new Date('2021-03-23T17:10:02');
  const now = new Date();
  const timeDiff = (now.getTime() - start.getTime());
  const msPerMinute = 60 * 1000;
  const msPerHour = 60 * msPerMinute;
  const msPerDay = 24 * msPerHour;
  const passDay = Math.floor(timeDiff / msPerDay);
  const passHour = Math.floor((timeDiff % msPerDay) / 60 / 60 / 1000);
  const passMinute = Math.floor((timeDiff % msPerHour) / 60 / 1000);
  const passSecond = Math.floor((timeDiff % msPerMinute) / 1000);
  display_live_time.innerHTML = " " + passDay + " 天 " + passHour + " 小时 " + passMinute + " 分 " + passSecond + " 秒";
}
blog_live_time();
</script></div></footer><a class="hty-icon-button" id="back-to-top" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a></div></body></html>